const Controller = require('egg').Controller 
const xss = require('xss')

function deleteEmptyProperty(object){
    for (var i in object) {
        var value = object[i];
        // sodino.com
        // console.log('typeof object[' + i + ']', (typeof value));
        if (typeof value === 'object') {
            if (Array.isArray(value)) {
                if (value.length == 0) {
                    delete object[i];
                    console.log('delete Array', i);
                    continue;
                }
            }
            deleteEmptyProperty(value);
            if (isEmpty(value)) {
                console.log('isEmpty true', i, value);
                delete object[i];
                console.log('delete a empty object');
            }
        } else {
            if (value === '' || value === null || value === undefined) {
                delete object[i];
                console.log('delete ', i);
            } else {
                console.log('check ', i, value);
            }
        }
    }
  }
  function isEmpty(object) {
    for (var name in object) {
        return false;
    }
    return true;
  }

class User extends Controller {
    async updateUser() {
        const { ctx } = this
        let { user_name = '', avatar = '', sign = '' ,publicKey = '' } = ctx.request.body;
        let id = ctx._id
        try {
            let data = { user_name:xss(user_name), avatar, sign, publicKey }
            deleteEmptyProperty(data)
            let res = await ctx.model.User.findOneAndUpdate({_id:id},{
                $set: data
            }, {new: true})
            if (res !== null) {
                ctx.body = {
                    code: 200,
                    msg: '更新数据成功',
                }
            } 
        } catch (e) {
            ctx.logger.error(e)
            ctx.body = {
                code: 500,
                msg: '更新失败，服务器异常！'
              }
        }
    }
}

module.exports = User